package com.xxl.job.executor.service.jobhandler;

import org.springframework.stereotype.Component;

import com.alibaba.datax.core.Engine;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.IJobHandler;
import com.xxl.job.core.handler.annotation.JobHandler;
import com.xxl.job.core.log.XxlJobLogger;


/**
 * 任务Handler示例（Bean模式）
 *
 * 开发步骤：
 * 1、继承"IJobHandler"：“com.xxl.job.core.handler.IJobHandler”；
 * 2、注册到Spring容器：添加“@Component”注解，被Spring容器扫描为Bean实例；
 * 3、注册到执行器工厂：添加“@JobHandler(value="自定义jobhandler名称")”注解，注解value值对应的是调度中心新建任务的JobHandler属性的值。
 * 4、执行日志：需要通过 "XxlJobLogger.log" 打印执行日志；
 *
 * @author xuxueli 2015-12-19 19:43:36
 */
@JobHandler(value="demoJobHandler")
@Component
public class DemoJobHandler extends IJobHandler {

	@Override
	public ReturnT<String> execute(String param) throws Exception {
		XxlJobLogger.log("XXL-JOB, Hello World.");

		System.setProperty("datax.home", getCurrentClasspath());
		String jsonPath = getCurrentClasspath() + "job/stream2stream.json";
		String[] datxArgs = { "-job", jsonPath, "-mode", "standalone", "-jobid", "-1" };
		try {
			Engine.entry(datxArgs);
		} catch (Throwable e) {
			return FAIL;
		}
		
		return SUCCESS;
	}

	public static String getCurrentClasspath() {
		ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
		String currentClasspath = classLoader.getResource("").getPath();
		// 当前操作系统
		String osName = System.getProperty("os.name");
		if (osName.startsWith("Windows")) {
			// 删除path中最前面的/
			currentClasspath = currentClasspath.substring(1);
		}
		return currentClasspath;
	}
}
